package com.WOWTradeNews.phone;

import java.lang.reflect.Field;
import java.util.List;
import java.util.TreeSet;

import org.json.JSONException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.WOWTradeNews.DataBase.News;
import com.WOWTradeNews.DataBase.SystemDBManager;
import com.WOWTradeNews.DataBase.ViewNews;
import com.WOWTradeNews.Util.ImageLoader;
import com.WOWTradeNews.Util.ImageLoader.OnDoneListener;
import com.WOWTradeNewsTest.R;

public class NewsListAdapter extends ArrayAdapter<News> {
    private ListView listView;
    //private AsyncImageLoader asyncImageLoader;
    private int newsType;
    
    public static final int VIEW_TYPE_NEWS 	  = 0;
    public static final int VIEW_TYPE_AD   	  = 1;
    public static final int VIEW_TYPE_COUNT     = 2;
    
    private TreeSet mSet = new TreeSet();
    
    boolean like = false;
    private SystemDBManager systemDBManager;
    ImageLoader loader;
    
    public NewsListAdapter(Activity activity, List<News> bonusList, ListView listView,int newsType, TreeSet set) {
        super(activity, 0, bonusList);
        this.listView = listView;
        //asyncImageLoader = new AsyncImageLoader();
        this.newsType=newsType;
        mSet = set;
        loader = new ImageLoader(activity);
    }
    
    public NewsListAdapter(Activity activity, List<News> bonusList, ListView listView,int newsType, TreeSet set,boolean like) {
        super(activity, 0, bonusList);
        this.listView = listView;
        //asyncImageLoader = new AsyncImageLoader();
        this.newsType=newsType;
        mSet = set;
        this.like = like;
        systemDBManager = new SystemDBManager(activity);
        loader = new ImageLoader(activity);
    }
    
    public View getView(int position, View convertView, ViewGroup parent) {
        final Activity activity = (Activity) getContext();

        final News news = getItem(position);
        if(news.isGj()) {
        	news.setSubject(news.getGjtitle());
        }
        int ad = news.flag;
        
        int type = getItemViewType(position);
        
        
        
        Log.d("zhaosdfa", "ad:" + ad);
        
        // Inflate the views from XML
        View rowView = convertView;
        ViewNews viewNews;
        if (rowView == null) {
            LayoutInflater inflater = activity.getLayoutInflater();
			if (type == VIEW_TYPE_NEWS) {
				rowView = inflater.inflate(
						R.layout.market_research_list_item_phone, null);
			} else {
				rowView = inflater.inflate(
						R.layout.ad_list_item, null);
				Log.d("zhaosdfa", "ad_list_item:" + rowView.toString());
			}
            viewNews = new ViewNews(rowView);
            rowView.setTag(viewNews);
        } else {
        	viewNews = (ViewNews) rowView.getTag();
        	Log.d("zhaosdfa", "rowView.getTag:" + viewNews.toString());
        }
        
        
        if(type == VIEW_TYPE_NEWS) {
        	// Load the image and set it on the ImageView
            //String imageFile = news.getImageUrl();
        	String imageFile = news.getImg1Url();
            final ImageView imageView = viewNews.getImageView();
    		//imageView.setLayoutParams(new RelativeLayout.LayoutParams(170,120));
    		imageView.setAdjustViewBounds(false);
    		imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
    		
    		RelativeLayout re = (RelativeLayout) rowView.findViewById(R.id.fav);
    		ImageView share = (ImageView) rowView.findViewById(R.id.share);
    		final ImageView note = (ImageView) rowView.findViewById(R.id.note);
    		if(news.getNote() != null && !news.getNote().equals("") && !news.getNote().equals("null")) {
    			note.setBackgroundResource(R.drawable.pimk);
    		} else {
    			note.setBackgroundResource(R.drawable.mb_note);
    		}
    		
    		if(like) {
    			final String content = news.getSubject();
    			re.setVisibility(View.VISIBLE);
    			share.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						Intent intent = new Intent(Intent.ACTION_SEND); 
						intent.setType("text/plain"); 
						 intent.putExtra(Intent.EXTRA_TEXT, content); 
						activity.startActivity(Intent.createChooser(intent, "選擇分享"));
					}
				});
    			
    			note.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						String str = systemDBManager.queryNote(news.getIid());
						news.setNote(str);
						if(str == null || str.equals("") || str.equals("null")) {
							str = "";
			    		} 
						final EditText etn_xx = new EditText(activity);
						etn_xx.setText(str);
						LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT, 350);
						etn_xx.setGravity(Gravity.TOP);
						etn_xx.setHeight(350);
						etn_xx.setLayoutParams(lp);
						
						new AlertDialog.Builder(activity).
						setTitle("註記").setView(etn_xx)
						.setPositiveButton("確認", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								Field field = null;
								String xx = etn_xx.getText().toString();
								if(TextUtils.isEmpty(xx)) {
									Toast.makeText(activity, "請輸入內容", Toast.LENGTH_SHORT).show();
									 try {
										field = dialog.getClass().getSuperclass().getDeclaredField("mShowing" );
										field.setAccessible(true);
									    field.set(dialog,false);
									    dialog.dismiss();
									} catch (NoSuchFieldException e) {
										e.printStackTrace();
									} catch (IllegalArgumentException e) {
										e.printStackTrace();
									} catch (IllegalAccessException e) {
										e.printStackTrace();
									}
								} else {
									systemDBManager.updateFav(xx, news.getIid());
									note.setBackgroundResource(R.drawable.pimk);
									try {
										field = dialog.getClass().getSuperclass().getDeclaredField("mShowing" );
										field.setAccessible(true);
										field.set(dialog, true);
										dialog.dismiss();
									} catch (NoSuchFieldException e) {
										e.printStackTrace();
									} catch (IllegalArgumentException e) {
										e.printStackTrace();
									} catch (IllegalAccessException e) {
										e.printStackTrace();
									}
								    
								}
							}
						})
						.setNegativeButton("取消", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								try {
									Field field = dialog.getClass()
								            .getSuperclass().getDeclaredField(
								                     "mShowing" );
								    field.setAccessible(true);
									field.set(dialog, true);
									dialog.dismiss();
								} catch(Exception e) {
									e.printStackTrace();
								}
							}
						})
						.create().show();
					}
				});
    		} else {
    			re.setVisibility(View.GONE);
    		}
    		
    		loader.DisplayImage(news.getImg1Url(), imageView, false, new OnDoneListener() {
				@Override
				public void onDone(Bitmap cachedImage) {
					if (cachedImage == null) {
		           		switch (newsType) {
		        		case 1:
		        			imageView.setImageResource(R.drawable.defaulticon1);
		            		break;
		        		case 2:
		        			imageView.setImageResource(R.drawable.defaulticon2);
		        			break;
		        		case 3:
		        			imageView.setImageResource(R.drawable.defaulticon3);
		        			break;
		        		case 4:
		        			imageView.setImageResource(R.drawable.defaulticon4);
		        			break;
		        		case 5:
		        			imageView.setImageResource(R.drawable.defaulticon5);
		        			break;
		        		}
		    		}else{			
		    			imageView.setImageBitmap(cachedImage);
		    		}
				}
			});
//            imageView.setTag(imageFile);  //TODO
    		
            /*Bitmap cachedImage = asyncImageLoader.loadBitmap(imageFile, new ImageCallback() {
                public void imageLoaded(Bitmap imageBitmap, String imageUrl) {
                    ImageView imageViewByTag = (ImageView) listView.findViewWithTag(imageUrl);
                    if (imageViewByTag != null) {
                    	if(imageBitmap!=null){
                    		imageViewByTag.setImageBitmap(imageBitmap);
                    	}else{
                    		switch (newsType) {
                    		case 1:
                        		imageViewByTag.setImageResource(R.drawable.defaulticon1);
                        		break;
                    		case 2:
                    			imageViewByTag.setImageResource(R.drawable.defaulticon2);
                    			break;
                    		case 3:
                    			imageViewByTag.setImageResource(R.drawable.defaulticon3);
                    			break;
                    		case 4:
                    			imageViewByTag.setImageResource(R.drawable.defaulticon4);
                    			break;
                    		case 5:
                    			imageViewByTag.setImageResource(R.drawable.defaulticon5);
                    			break;
                    		}
                    	}
                    }
                }
            });*/
            
//            Bitmap cachedImage = news.getImg();  //TODO
            
    		

            TextView idText=viewNews.getIdText();
            //idText.setText(news.getPK_ID());
            idText.setText(news.getIid());
            TextView textView = viewNews.getTitleText();
            //textView.setText(news.getTitle());
            textView.setText(news.getSubject());
            TextView contentView = viewNews.getSummaryText();                
            //contentView.setText(news.getSummary());
        } else {	//AD
        	String url = news.getTxt1Url();
        	TextView textView = viewNews.getAdUrl();
        	textView.setText(url);
        	
        	String imgUrl = news.getImg1Url();
        	//Log.d("zhaosdfa", "flag:" + news.flag + ",imgUrl:" + imgUrl);
        	//print(news);
        	Log.d("zhaosdfa", viewNews.toString());
        	final ImageView img = viewNews.getAdImageView();
        	img.setTag(imgUrl);
        	//imageView.setLayoutParams(new RelativeLayout.LayoutParams(170,120));
    		img.setAdjustViewBounds(false);
    		img.setScaleType(ImageView.ScaleType.CENTER_CROP); 
        	
        	/*Bitmap cachedImage = asyncImageLoader.loadBitmap(imgUrl, new ImageCallback() {
                public void imageLoaded(Bitmap imageBitmap, String imageUrl) {
                    ImageView imageViewByTag = (ImageView) listView.findViewWithTag(imageUrl);
                    if (imageViewByTag != null) {
                    	if(imageBitmap!=null){
                    		imageViewByTag.setImageBitmap(imageBitmap);
                    	}else{
                    		switch (newsType) {
                    		case 1:
                        		imageViewByTag.setImageResource(R.drawable.defaulticon1);
                        		break;
                    		case 2:
                    			imageViewByTag.setImageResource(R.drawable.defaulticon2);
                    			break;
                    		case 3:
                    			imageViewByTag.setImageResource(R.drawable.defaulticon3);
                    			break;
                    		case 4:
                    			imageViewByTag.setImageResource(R.drawable.defaulticon4);
                    			break;
                    		case 5:
                    			imageViewByTag.setImageResource(R.drawable.defaulticon5);
                    			break;
                    		}
                    	}
                    }
                }
            });*/
        	
//    		Bitmap cachedImage = news.getImg(); //TODO
    		loader.DisplayImage(news.getImg1Url(), img, false, new OnDoneListener() {
				@Override
				public void onDone(Bitmap cachedImage) {
					if (cachedImage == null) {
						switch (newsType) {
		        		case 1:
		        			img.setImageResource(R.drawable.defaulticon1);
		            		break;
		        		case 2:
		        			img.setImageResource(R.drawable.defaulticon2);
		        			break;
		        		case 3:
		        			img.setImageResource(R.drawable.defaulticon3);
		        			break;
		        		case 4:
		        			img.setImageResource(R.drawable.defaulticon4);
		        			break;
		        		case 5:
		        			img.setImageResource(R.drawable.defaulticon5);
		        			break;
		        		}
		    		}else{			
		    			img.setImageBitmap(cachedImage);
		    		}
				}
			});
    		
        }
        

        return rowView;
    }    
    
    
    private void print(News news) {
    	Log.d("zhaosdfa", "iid:"+news.getAdIid() + ",title:" + 
    news.getAdTitle() + ",alinks:" + news.getAdPath() + ",img:" + news.getAdImgPath() );
    }

    @Override
    public int getViewTypeCount() {
    	return VIEW_TYPE_COUNT;
    }
    
    @Override
    public int getItemViewType(int position) {
        return mSet.contains(position) ? VIEW_TYPE_AD : VIEW_TYPE_NEWS;
    }
    
    
    
}
